package servlet.home;

import com.alibaba.fastjson.JSONObject;
import com.mysql.jdbc.StringUtils;
import dao.UserDao;
import dao.UserDaoImpl;
import po.User;
import utils.JdbcUtil;
import utils.ResultData;

import javax.jws.soap.SOAPBinding;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 *          修改密码
 */
@WebServlet(urlPatterns = "/change")
public class Change extends HttpServlet {
    JdbcUtil jdbcUtil = new JdbcUtil();

    @Override
    public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method.equals("updatePwa") && method !=null){
            this.updataPwa(req,res);
        }
    }

    protected void updataPwa(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Connection connection = jdbcUtil.getConnection();
        //从Session里面拿id
        Object o = req.getSession().getAttribute("userKey");
        String paw = req.getParameter("paw");
        String npaw = req.getParameter("newpaw");
        boolean flag = false;

        if (!((User)o).getPassword().equals(paw)){
            req.setAttribute("message","原始密码有误");
            req.getRequestDispatcher("/password.html").forward(req,resp);
        }else {

            if ((o!= null) && (!StringUtils.isNullOrEmpty(npaw))){
                UserDao userDao = new UserDaoImpl();
                flag = userDao.updatePwd(((User)o).getId(),npaw);
                if (flag){
                    req.setAttribute("message","修改成功");
                    //修改成功，移除Session
                    req.getSession().removeAttribute("userKey");
                    //跳转到登陆页面
                    resp.sendRedirect("/login.html");
                }else {
                    req.setAttribute("message","修改失败");
                    req.getRequestDispatcher("/password.html").forward(req,resp);
                }
            }else {
                req.setAttribute("message","修改出错");
                req.getRequestDispatcher("/password.html").forward(req,resp);
            }
        }
        }
    }

